<?php

//if (version_compare(PHP_VERSION, '5.6.0', '<')) die('require PHP > 5.6.0 !');

define('APP_ROOT', dirname(__DIR__));
define('SITE_URL', 'http://' . $_SERVER['HTTP_HOST'] . substr($_SERVER['PHP_SELF'], 0, -10));

date_default_timezone_set('Asia/Shanghai');

//  第三方库自动加载
require APP_ROOT . '/../vendor/autoload.php';

//  自定义路由处理
$router = new AltoRouter();

//require APP_ROOT . '/config/routes.php';

/*$router->map( 'GET', '/', function() {
    echo "hello /";
    //require __DIR__ . '/views/home.php';
});
// map user details page
$router->map( 'GET', '/user/[i:id]/', "user_controller#detail");*/
$router->map('GET|POST', '/[a:controllerName]/[a:actionName]', function ($controllerName, $actionName) {
    runAction($controllerName, $actionName, []);
});

$router->map('GET|POST', '/[a:controllerName]/[a:actionName]/?[**:]', function ($controllerName, $actionName) {
    $args = explode('/', $_SERVER['REQUEST_URI']);
    $args = array_slice($args, 3);
    runAction($controllerName, $actionName, $args);
});
$match = $router->match();

// match current request url

if( $match && is_callable( $match['target'] ) ) {
    call_user_func_array( $match['target'], $match['params'] );
} else {
    // no route was matched
    list($controller,$action)=explode("#",$match['target']);
    if(!method_exists($class_name,$action)){
        header( $_SERVER["SERVER_PROTOCOL"] . ' action Not Found');
    }
    //$file_path= APP_ROOT . "/controllers/".$controller.".php";
    //include $file_path;
    /*$class="\\app\\controllers\\".$controller;
    $class_name=new $class();
    if(method_exists($class_name,$action)){
        $class_name->$action();
    }else {
        header( $_SERVER["SERVER_PROTOCOL"] . ' action Not Found');
    }*/
    runAction($controllerName, $actionName, $match['params']);

}
function runAction($controllerName, $actionName, $args)
{
    // echo $controllerName;
    $controllerClass = '\app\controllers\\' . ucfirst($controllerName) . '_controller';
    if (!class_exists($controllerClass)) {
        exit($controllerName . ' Class Not Found!');
    }
    $controller = new $controllerClass();
    if (method_exists($controller, $actionName)) {
        $controller->$actionName(...$args);
    } else {
        exit($actionName . ' Action Not Found!');
    }
}
// load map routes

